import React = require("react");
import { ComponentStatus, ShoppingCart, ShoppingCartState } from "./component";
import { component } from "components/common/component";
import { subscribe, asyncComponentState } from "common";
import { defaultNavBar } from "mobile/site";
import { BaseComponent } from "components/common/base-component";
import { ShoppingCartFooter } from "./shopping-cart-footer";



@component()
export class ShoppingCartHeader extends BaseComponent<any, Partial<ShoppingCartState>> {
    private _shoppingCart: ShoppingCart;
    _shoppingCartFooter: any;

    constructor(props) {
        super(props);
        this.state = {};
    }


    private edit() {
        // this.shoppingCart.edit();
        // if (this.shoppingCart.status.value == "edit")
        //     this.shoppingCart.status.value = "normal";
        // else
        //     this.shoppingCart.status.value = "edit";
        this.setState({ editSelectedItems: [] })
        let status = this.state.status;
        console.assert(status != null);
        if (status == "edit") {
            this.setState({ status: "normal" });
        }
        else {
            this.setState({ status: "edit" });
        }
    }
    get shoppingCart(): ShoppingCart {
        if (this._shoppingCart == null) {
            let components = this.masterPage.childComponents[ShoppingCart.name] || [];
            let c = components[0] as ShoppingCart;
            console.assert(c != null);
            this._shoppingCart = c as any as ShoppingCart;
        }

        return this._shoppingCart;
    }

    get shoppingCartFooter(): ShoppingCartFooter {
        if (this._shoppingCartFooter == null) {
            let components = this.masterPage.childComponents[ShoppingCartFooter.name] || [];
            this._shoppingCartFooter = components[0];
            console.assert(this._shoppingCartFooter != null);
        }

        return this._shoppingCartFooter;
    }

    componentDidMount() {
        setTimeout(() => {
            // 必须要延时,才能获取到控件
            console.assert(this.shoppingCart != null);
            asyncComponentState(this.shoppingCart, this, "status", "editSelectedItems");
            asyncComponentState(this.shoppingCartFooter, this, "status");
        }, 100);
    }
    render() {
        let { status } = this.state;
        let showBackButton = true;
        return defaultNavBar(this.page, {
            title: '购物车',
            right:
                <button className="right-button" style={{ width: 'unset' }}
                    onClick={async () => {
                        await this.edit();
                        this.setState({ status: this.shoppingCart.state.status });
                    }}>
                    {status == 'normal' ? '编辑' : '完成'}
                </button>,
            showBackButton

        });
    }
}
